package com.cafuc.jdk8;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamApi {

    public void streamTest() {
        List<String> aa = new ArrayList<>();
        aa.add("cdscas");
        aa.add("rrrr");
        aa.add("sss");
        aa.add("gg");
        aa.add("hhhh");

        // list 创建流
        aa.stream()
                .filter(item -> item.contains("r") || item.contains("g"))
                .sorted((o1, o2) -> o1.compareTo(o2))
                .forEach(System.out::println);
        // 数组创建流
        String[] array = new String[]{"asdfg", "asdfghj", "tytyty"};
        System.out.println(array);
        Arrays.stream(array).forEach(System.out::println);
        // 值来创建流
        Stream.of("sun", "smk", "ddddfffff").forEach(System.out::println);
        // 函数创建流
        Stream.iterate(0, i -> i + 2).limit(20).forEach(System.out::println);
        Stream.generate(new Random() :: nextInt).limit(10).forEach(System.out::println);

        List<Integer> list = Arrays.asList(1,3,4,5,11,7,7,16);
        List<Integer> list2 = list.stream()
                .distinct()
                .map(item -> item * 2)
                .filter(item -> item % 1 == 0)
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());
        System.out.println(list2);
        Integer[] array1 = list.stream()
                .distinct()
                .map(item -> item * 2)
                .filter(item -> item % 1 == 0)
                .sorted(Comparator.reverseOrder())
                .toArray(Integer[] :: new);
        System.out.println(array1);

        Map<String, String> map1 = new HashMap<>();
        map1.put("aaa","rrrrrwwww");
        map1.put("ddd","rrrrrtttt");
        map1.put("eee","vyyyyyyuu");
        map1.put("bbb","uuuuuuiii");
        map1.put("ccc","nnnnmmmmm");
        map1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(System.out::println);
        Map<String,String> map2 = map1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry :: getKey,
                        Map.Entry :: getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));
        System.out.println(map2);
        String keys = map1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(item -> item.getKey())
                .collect(Collectors.joining());
        System.out.println(keys);
    }

    public static void main(String[] args) {
        StreamApi streamApi = new StreamApi();
        streamApi.streamTest();
    }
}

